clc; clearvars; close all;
addpath('LSGO2013\')
addpath('LSGO2013\datafiles\');
load 'f07.mat';
global initial_flag

NS = 50;   % 种群数
dim = 1000;   % 种群维度
upperBound = ub;
lowerBound = lb;
bestYhistory = [];    % 保存每次迭代的最佳值
trueGroup = [50, 25, 25, 100, 50, 25, 25, 700];

for funcNum = 7

    initial_flag = 0;    % 换一个函数initial_flag重置为0
    sampleX = lhsdesign(NS, dim) .* (upperBound - lowerBound) + lowerBound .* ones(NS, dim);    % 生成NS个种群,并获得其评估值
    sampleY = benchmark_func(sampleX', funcNum);
    sampleY = sampleY';     % 每一列是一个种群
    [bestY, bestIndex] = min(sampleY);    % 获取全局最小值以及对应的种群
    lastBestY = bestY;
    bestX = sampleX(bestIndex, :);
    bestYhistory = [bestYhistory; bestY];
    evalue = 50;

    allGroups = {};     % 理想分组
    s1 = size(trueGroup, 2);
    for i0 = 1 : s1
        if i0 == 1
            start = 1;
        else
            start = start + trueGroup(i0 - 1);
        end
        endstart = start + trueGroup(i0) - 1;
        allGroups{end + 1} = p(1, start : endstart);
    end

    deltaF = zeros(1, s1);
    version = 2;

    while evalue < 3 * 10 ^ 6
        for i1 = 1 : s1
            index1 = allGroups{i1};
            dim1 = size(index1, 2);
            subX = sampleX(:, index1);
            subX = SaNSDE(subX, sampleY, bestX, index1, 100, dim1, lowerBound, upperBound, @(x)benchmark_func(x, funcNum));
            sampleX(:, index1) = subX;
            sampleY = benchmark_func(sampleX', funcNum);
            sampleY = sampleY';
            [bestY, bestIndex] = min(sampleY);    % 获取全局最小值以及对应的种群
            bestX = sampleX(bestIndex, :);
            deltaF(1, i1) = deltaF(1, i1) + lastBestY - bestY;
            lastBestY = bestY;
            evalue = evalue + 50 * 100;
        end

        delta0 = 1;
        [~, index2] = max(deltaF);
        index1 = allGroups{index2};
        while delta0 == 1 || delta0 / lastBestY > 0.0001
            dim1 = size(index1, 2);
            subX = sampleX(:, index1);
            subX = SaNSDE(subX, sampleY, bestX, index1, 100, dim1, lowerBound, upperBound, @(x)benchmark_func(x, funcNum));
            sampleX(:, index1) = subX;
            sampleY = benchmark_func(sampleX', funcNum);
            sampleY = sampleY';
            [bestY, bestIndex] = min(sampleY);    % 获取全局最小值以及对应的种群
            bestX = sampleX(bestIndex, :);
            delta0 = lastBestY - bestY;
            deltaF(1, index2) = deltaF(1, index2) + delta0;
            lastBestY = bestY;
            if version == 1
                delta0 = 0;
            end
            evalue = evalue + 50 * 100;
            disp(evalue);
            disp(bestY);
        end
        bestYhistory = [bestYhistory; bestY];
        disp(evalue);
    end
end
plot(bestYhistory);
save('CCBCDG.mat','bestYhistory');
legend('Y','Location', 'northeast');